'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
    config = require(path.resolve('./config/config')),
    expressJwt = require('express-jwt'),
    mongoose = require('mongoose'),
    User = mongoose.model('User');

/**
 * Module init function.
 */
module.exports = function(app) {
    app.use(['/api/entity', '/api/password', '/api/users', '/api/Kanban', '/api/ConnectArea'], expressJwt({
        secret: config.jwtTokenSecret,
        isRevoked: function (req, payload, done) {
            User.findOne({Code: payload.Code}, function (err, user) {
                if (err) {
                    return done(err);
                } else {
                    if (!user) {
                        return done({
                            status: 'EEEE',
                            desc: '不存在该用户'
                        });
                    } else {
                        return done(null, !user.IsEffective);
                    }
                }
            });
        }
    }));
    app.use(function(err, req, res, next) {
        if (err.name === 'UnauthorizedError') {
            res.json({
                status: '4001',
                desc: '认证失败'
            });
        }
    });
};
